﻿@{
    ViewBag.PageTitle = Resources.Intercamber.Moderate_PageName;
}
@section PageHead
{
    <link href="~/Content/Discussions.css?@ViewBag.VersionNumber" rel="stylesheet" />
    <style>
        .tipWidth {
            max-width: 800px !important;
        }

        .msgCell {
            white-space: initial !important;
        }
    </style>
    <script type="text/javascript">
        var texts = {
            ModerationEdition: "@(Resources.Intercamber.Moderate_ModerateEdition)",
            AskedByAbout: "@(Resources.Intercamber.Moderate_AskedByAbout)",
            Date: "@(Resources.Intercamber.Date)",
            Message: "@(Resources.Intercamber.Message)",
            Resolved: "@(Resources.Intercamber.Moderate_Resolved)",
            MarskAsRevolved: "@(Resources.Intercamber.Moderate_MarskAsRevolved)",
            ModeratorComment: "@(Resources.Intercamber.Moderate_ModeratorComment)",
            BlockX: "@(Resources.Intercamber.Moderate_BlockX)",
            ViewProfilX: "@(Resources.Intercamber.Moderate_ViewProfilX)",
            BlockUserConfirm: "@(Resources.Intercamber.Moderate_BlockUserConfirm)",
            UserBlocked: "@(Resources.Intercamber.Moderate_UserBlocked)",
        };

        var moderationManager = new function() {

            var ttAdd = null, ttBlock = null;
            this.isCreatingNew = false;
            var editedId = null;
            this.openPopupAdd = function() {
                if (ttAdd == null) {
                    ttAdd = $('<div />');
                    ttAdd.qtip({
                        show: {
                            effect: false,
                            modal: { on: true, blur: false }
                        },
                        content: $('#ttAdd'),
                        position: { my: 'center', at: 'center', target: $(window), viewport: $(window), adjust: { method: "shift", x: 0, y: 0 }, effect: false },
                        events: {
                            show: function() {
                                //$(this).draggable();
                                $(this).qtip('option', { 'content.title': texts.ModerationEdition, 'content.title.button': 'true' });
                            },
                            hide: function() {
                                $(this).qtip('option', { 'position.my': 'top left', 'position.target': [$(this).offset().left, $(this).offset().top] });
                            }
                        },
                        hide: false,
                        style: { classes: "qtip-bootstrap qtip-rounded tipWidth", tip: false }
                    });
                }

                var data = $("#gridModerations").getRowData(editedId);

                $("#requestDetail").html(
                    texts.AskedByAbout.replace("{0}", data.LblUserCreated).replace("{1}", data.LblUserTarget) + "<br/>" +
                        texts.Date + ": " + data.DateCreatedStr + "<br/><br/>" +
                        texts.Message + ": " + data.Message + "<br/><br/>" +
                        texts.ModeratorComment + "<br/><textarea id='resolveMessage' style='border:1px solid lightgray; width:350px;' rows='6'>" + data.ResolveMessage + "</textarea><br/>" +
                    (data.DateResolvedStr != "" ?
                        texts.Resolved + ": " + data.DateResolvedStr : "") +
                        "<input type='checkbox' id='resolved'><label for='resolved'>" + texts.MarskAsRevolved + "</label>" +
                        "<br/><br/>");


                $("#blockBtnLbl").html(texts.BlockX.replace("{0}", data.LblUserTarget));
                $("#blockBtn").click(function() {
                    $("#blockMessage").val("");
                    ttBlock = $('<div />');
                    ttBlock.qtip({
                        show: {
                            effect: false,
                            modal: { on: true, blur: false }
                        },
                        content: $('#ttBlock'),
                        position: { my: 'center', at: 'center', target: $(window), viewport: $(window), adjust: { method: "shift", x: 0, y: 0 }, effect: false },
                        events: {
                            show: function() {
                                $(this).draggable();
                                $(this).qtip('option', { 'content.title': texts.BlockX.replace("{0}", data.LblUserTarget), 'content.title.button': 'true' });
                            },
                            hide: function() {
                                $(this).qtip('option', { 'position.my': 'top left', 'position.target': [$(this).offset().left, $(this).offset().top] });
                            }
                        },
                        hide: false,
                        style: { classes: "qtip-bootstrap qtip-rounded tipWidth", tip: false }
                    });
                    ttBlock.qtip("show");
                });
                $("#profilBtnLbl").html(texts.ViewProfilX.replace("{0}", data.LblUserTarget));
                $("#profilBtn").click(function() {
                    profilViewerManager.showProfil(data.IdUserTarget);
                });

                $("#resolveMessage").val(data.ResolveMessage);
                $("#resolved").prop("checked", data.DateResolvedStr != "");

                userDiscussion = [{
                        name: data.LblUserCreated,
                        id: data.IdUserCreated,
                        color: "#057A97",
                    }, {
                        name: data.LblUserTarget,
                        id: data.IdUserTarget,
                        color: "#F36507",
                    }];
                var ctx = data.Context;
                if (ctx.indexOf("Discussion;") == 0) {
                    var idThread = parseInt(ctx.replace("Discussion;", ""));
                    moderationManager.loadChat(idThread, null, true);
                }

                ttAdd.qtip('show');
            };

            this.popupHide = function() {
                ttAdd.qtip('hide');
            };
            this.blockPopupHide = function() {
                ttBlock.qtip('hide');
            };

            this.init = function() {
                $("#gridModerations").jqGrid({
                    //autowidth: true,
                    datatype: 'json',
                    width: '100%',
                    height: '100%',
                    jsonReader: { 'repeatitems': false, 'id': 'IdModeration' },
                    loadonce: true,
                    url: '/Admin/ModerationData',
                    viewrecords: true,
                    colModel: [
                        { name: 'IdModeration', hidden: true },
                        { name: 'IdUserCreated', hidden: true },
                        { name: 'EstUserCreated', hidden: true },
                        { name: 'IdUserTarget', hidden: true },
                        { name: 'LblUserTarget', hidden: true },
                        { name: 'EstUserTarget', hidden: true },
                        { name: 'Context', hidden: true },
                        { name: 'EnAttente', hidden: true },
                        { name: 'Blocked', hidden: true },
                        { name: 'IdModeration', fixed: true, formatter: moderationManager.gridColumnEdit, label: '@Resources.Intercamber.Edit', resizable: false, sortable: false, width: 30, index: 'IdEstablishment', align: 'center' },
                        { name: 'LblUserCreated', label: '@Resources.Intercamber.User', align: 'center' },
                        { name: 'Message', label: '@Resources.Intercamber.Message', align: 'center', classes: 'msgCell' },
                        { name: 'DateCreatedStr', label: '@Resources.Intercamber.Moderate_DateCreation', align: 'center' },
                        { name: 'LblUserTarget', formatter: moderationManager.gridColumnLblUserTarget, label: '@Resources.Intercamber.Moderate_UserReported', align: 'center' },
                        { name: 'DateResolvedStr', label: '@Resources.Intercamber.Moderate_DateResolved', align: 'center' },
                        { name: 'ResolveMessage', label: '@Resources.Intercamber.Moderate_ResolveMessage', align: 'center' },
                    ],
                    subGrid: false,
                    loadComplete: function() {
                        $("#gridModerations").jqGrid('setGridWidth', 800, true);
                    },
                }).trigger("reloadGrid", [{ page: 1 }]);

                $("#valBlockUser").click(function() {
                    var data = $("#gridModerations").getRowData(editedId);
                    if (confirm(texts.BlockUserConfirm)) {
                        $.ajax({
                            type: "POST",
                            url: "/Admin/ModerationBlockUser",
                            contentType: "application/json; charset=utf-8",
                            data: JSON.stringify({
                                idUser: data.IdUserTarget,
                                comment: $("#blockMessage").val()
                            }),
                            dataType: "json",
                            success: function(result) {
                                if (result == true) {
                                    moderationManager.blockPopupHide();
                                    moderationManager.reloadGrid();
                                }
                            },
                            error: function(result) {
                                alert("Service error!");
                                debugger;
                            }
                        });

                        moderationManager.blockPopupHide();
                    }
                });
            };

            this.reloadGrid = function() {
                $("#gridModerations").jqGrid().setGridParam({ datatype: 'json', page: 1 }).trigger('reloadGrid');
            };

            this.gridColumnEdit = function(cellvalue, options, rowobject) {
                return "<img id=\"add" + cellvalue + "\" title=\"\" class='imgButton' src='/Images/Edit.gif' onclick=\"moderationManager.edit(" + cellvalue + ");\" />";
            };
            this.gridColumnLblUserTarget = function(cellvalue, options, rowobject) {
                var blk = rowobject.Blocked;
                return rowobject.LblUserTarget + (blk ? "<br/><i>" + texts.UserBlocked + "</i>" : "");
            };

            this.edit = function(id) {
                editedId = id;
                moderationManager.openPopupAdd(false);
            };

            this.save = function() {
                this.popupHide();
                $("#loading").show();
                var jsonParams = JSON.stringify({
                    DateResolved: $("#resolved").prop("checked") ? new Date() : null,
                    ResolveMessage: $("#resolveMessage").val(),
                    IdModeration: editedId
                });

                $.ajax({
                    type: "POST",
                    url: "/Admin/UpdateModeration",
                    contentType: "application/json; charset=utf-8",
                    data: jsonParams,
                    dataType: "json",
                    success: function(result) {
                        $("#loading").hide();
                        if (result == true) {
                            moderationManager.reloadGrid();
                        } else {
                            alert("Error!");
                        }
                    },
                    error: function(result) {
                        $("#loading").hide();
                        alert("Service error!");
                        debugger;
                    }
                });
                ttAdd.qtip('hide');
            };

            // load chat in right div 
            var userDiscussion = [];
            var currentDiscussionDate = null, firstDiscussionDate = null, currentDiscussionThreadId = null;
            this.loadChat = function(id, idLastMess, scrollBottom) {
                if (id != null)
                    currentDiscussionThreadId = id;
                // load chat history 
                $.ajax({
                    type: "POST",
                    url: "/Talk/ChatHistory",
                    contentType: "application/json; charset=utf-8",
                    data: "{'idThread':\"" + currentDiscussionThreadId + "\", 'messageIdMax':" + idLastMess + "}",
                    dataType: "json",
                    success: function(result) {
                        $(".loadmore").remove();
                        $(".initialDate").remove();
                        for (var i = 0; i < result.d.length; i++) {
                            var r = result.d[i];
                            if (r.Action == null)
                                printDicussionMessage(r.Id, r.IdUser, r.Message, r.Correction, r.Date, false);
                        }
                        if (result.d.length > 0 && currentDiscussionDate != null)
                            $('#discussion').prepend("<span class='dateItem initialDate'>" + (new Date(currentDiscussionDate)).toLocaleDateString() + "</span>");
                        if (result.ps == result.d.length && result.d.length > 0)
                            $('#discussion').prepend("<span class='loadmore' onclick=\"moderationManager.loadChat(null," + result.d[result.d.length - 1].Id + ", false)\">@Resources.Intercamber.Discussion_LoadMoreMessages</span>");
                        if (scrollBottom)
                            scrollToDiscussionBottom();
                    },
                    error: function(result) {
                        debugger;
                    }
                });
            };

            function printDicussionMessage(id, Idsender, message, correction, date, appendBottom) {
                if (typeof(date) == "string")
                    date = instanciateDotNetDate(date);
                var dTime = new Date(date);
                dTime.setHours(0, 0, 0, 0);
                dTime = dTime.getTime();
                if (firstDiscussionDate == null)
                    firstDiscussionDate = dTime;
                var sender = Idsender == userDiscussion[0].id ? userDiscussion[0] : userDiscussion[1];
                var res = "<div class=\"msg\"'>" +
                    "<span class='msgHead'>" + date.toLocaleTimeString() + ' <label style="color:' + sender.color + '"> ' + sender.name + "</label>:&nbsp;</span> " +
                    "<span class='bubble " + (Idsender == userDiscussion[0].id ? "bubble2" : "bubble1") + " msgTxt'><div class='arrowLeft1'></div> <label class='message' id='m" + id + "' sender=\"u" + sender.id + "\">" + message + '</label></span></div>';
                var dateRes = "";
                if ((!appendBottom && (currentDiscussionDate == null || dTime != currentDiscussionDate)) || (appendBottom && firstDiscussionDate != dTime)) {
                    if (currentDiscussionDate != null)
                        dateRes += "<span class='dateItem'>" + (new Date(currentDiscussionDate)).toLocaleDateString() + "</span>";
                    if (!appendBottom)
                        currentDiscussionDate = dTime;
                    else
                        firstDiscussionDate = dTime;
                }

                if (appendBottom)
                    $("#discussion").append(dateRes + res);
                else
                    $("#discussion").prepend(res + dateRes);
                if (correction != null && correction != "")
                    addMessageCorrection(id, correction);
            }

            function addMessageCorrection(id, correction) {
                var dc = $("#tc" + id);
                if (dc == null || dc.length == 0) {
                    var dd = $("#m" + id);
                    if (dd == null || dd.length == 0) return;
                    printCorrectionFormated(dd, id, correction);
                } else
                    dc.html(correction);
            }

            function printCorrectionFormated(parentEl, id, correction) {
                parentEl.append("<div id='c" + id + "' class='correction'><div class='bubble bubble3'><div class='arrowTop'></div><label class='message' id='ct" + id + "'>" + correction + '</label></div></div>');
            }

            function scrollToDiscussionBottom() {
                var discussionDiv = $('#discussion');
                discussionDiv.scrollTop(discussionDiv[0].scrollHeight);
            }

        };

        $(function() {
            $(".jqbutton").button();
            moderationManager.init();
        });

    </script>
    @Html.Partial("~/Views/Shared/_ProfilViewerPartial.cshtml")
}

@section PageLeftBar {
    @Html.Partial("~/Views/Shared/_LeftBarUserDetailPartial.cshtml")
}

@section PageContent {
    <div class="innerTitle ui-corner-all">
        @Resources.Intercamber.Moderate_PageName
    </div>
    <br />
    <br />
    <div>
        <span id="loading" style="display: none;">
            <img src="~/Images/Loading.gif" />
            @Resources.Intercamber.Loading
        </span>
    </div>
    <table id="gridModerations" style="width: 100%"></table>

    <div id="ttAdd" style="display: none; width: 800px; position: relative;vertical-align: top;">
        <div id="discussion" style="float:right; width:400px; border-left: 1px dotted lightgray; height:400px;margin-right:25px; overflow: auto; padding: 5px;">
        </div>
        <label id="requestDetail"></label>
        <br />
        <div class="ttButtons">
            <button class="jqbutton" onclick="moderationManager.save(); return false; ">
                <img style="vertical-align: top; margin: 5px;" src="/Images/Save.png" />
                @Resources.Intercamber.Save
            </button>
            &nbsp;
            <button class="jqbutton" onclick="moderationManager.popupHide(); return false;">
                <img style="vertical-align: top; margin: 5px;" src="/Images/Back.png" />
                @Resources.Intercamber.Cancel
            </button>
            <div style="margin-top:10px">
                <button class="jqbutton" onclick="return false;" id="profilBtn">
                    <img style="vertical-align: top; margin: 5px;" src="/Images/Avatar.png" />
                    <label id="profilBtnLbl"></label>
                </button>
                
            </div>
            <div style="margin-top:10px">
                <button class="jqbutton" onclick="return false;" id="blockBtn">
                    <img style="vertical-align: top; margin: 5px;" src="/Images/Lock.png" />
                    <label id="blockBtnLbl"></label>
                </button>
                
            </div>
        </div>
    </div>
    <div id="ttBlock" style="display: none">
        <label >@Resources.Intercamber.Moderate_CommentBlock</label><br />
        <textarea id="blockMessage" style="border:1px solid lightgray;" rows="5"></textarea>
        <br />
        <div class="ttButtons">
            <button class="jqbutton" id="valBlockUser">
                <img style="vertical-align: top; margin: 5px;" src="/Images/Lock.png" />
                @Resources.Intercamber.Moderate_BlockUser
            </button>
            &nbsp;
            <button class="jqbutton" onclick="moderationManager.blockPopupHide();">
                <img style="vertical-align: top; margin: 5px;" src="/Images/Back.png" />
                @Resources.Intercamber.Cancel
            </button>
        </div>
    </div>
}

